#include "reader.h"
#include "common.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>

void TimeError(int year,int month,int day);

Reader * InitReader(){
	Reader * NewReader;
	NewReader=(Reader *)malloc(sizeof(Reader));
	NewReader->Name=NULL;
	NewReader->Year=0;
	NewReader->Month=0;
	NewReader->Day=0;
	NewReader->Next=NULL;
	return NewReader;
}

void Destroy_Reader(Reader* R){
	Reader * del;
	while (R != NULL){
		del=R;
		free(R->Name);
		R=R->Next;
		free(del);
	}
}

void Free_Reader(Reader * R){
	free(R->Name);
	free(R);
}

// 1 -> 2 -> 3 -> n
bool Delete_Reader(Reader ** R,char id[]){
	Reader * tmp,*last;
	if(*R == NULL)
		return false;
	if(strcmp((*R)->ID,id) == 0){
		tmp=*R;
		*R=tmp->Next;
		Show_Reader(tmp);
		Free_Reader(tmp);
		return true;
	}
	tmp = (*R)->Next;
	last= *R;
	while(tmp != NULL){
		if(strcmp(tmp->ID,id) == 0){
			Show_Reader(tmp);
			last->Next=tmp->Next;
			Free_Reader(tmp);
			return true;
		}
		tmp=tmp->Next;
		last=last->Next;
	}
	return false;
}

bool SetReturnTime(Reader * R,int year,int month,int day){
	time_t rawtime;
	time(&rawtime);
	struct tm * timeinfo;
	if(month > 12 || day > 30){
		TimeError(year,month,day);
		return false;
	}
	timeinfo = localtime(&rawtime);
	int NowYear=timeinfo->tm_year+1900;
	int NowMonth=timeinfo->tm_mon+1;
	int NowDay=timeinfo->tm_mday;
	int y=year-NowYear;
	int m=month-NowMonth;
	int d=day-NowDay;
	if(d < 0){
		m=m-1;
		d=d+30;
	}
	if(m < 0){
		y=y-1;
		m=m+12;
	}
	if(y < 0){
		TimeError(year,month,day);
		return false;
	}
	R->Year=year;
	R->Month=month;
	R->Day=day;
	return true;
}

void SetName_Reader(Reader * R,char name[]){
	int length=strlen(name);
	char * ch=(char *)malloc(sizeof(char)*(length+1));
	if(R->Name != NULL){
		free(R->Name);
		R->Name=NULL;
	}
	strcpy(ch,name);
	R->Name=ch;
}

void SetId_Reader(Reader * R,char id[]){
	strcpy(R->ID,id);
}

void Show_Reader(Reader * R){
	printf("===========================\n");
	printf("姓名: %s\n",R->Name);
	printf("约定归还日期: %d/%d/%d\n",R->Year,R->Month,R->Day);
	printf("===========================\n");
}

void TimeError(int year,int month,int day){
	printf("%d/%d/%d 不合法！\n",year,month,day);
}
bool GetId_Reader(char *isbn){
	int i=0;
	char ch;
	do{
		ch=getchar();
		if(i<11) {
			isbn[i]=ch;
			if(ch < '0' || ch > '9'){
				if(ch != '\n')
					clear_buffer();
				return false;
			}
		}
		++i;
	}while(ch != '\n');
	isbn[11]='\0';
	if(i == 12)
		return true;
	else
		return false;
}
